package com.jcli._socket基恩士客户端;


import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 1.新增正则表达式过滤写入表格数据。
 * 2.新增发送功能，查看功能是否完整。
 * -3.想加入各种进制选择与发送功能。
 * 4.按日期保存文件
 * 5.更改界面风格与字体大小
 * 6.优化代码-界面布局，多线程处理，命名规范
 * 7.点击启动响应慢 ，待解决。
 */
public class SocketClient extends JFrame {
    private JTextField ipField;
    private JTextField portField;
    private JButton connectButton;
    private JButton disconnectButton;
    private JTextArea receivedDataArea;
    private Socket socket;
    private PrintWriter out;
    private BufferedReader in;
    private Font f1 = new Font("楷体", Font.BOLD | Font.ITALIC, 16);
    private Font f2 = new Font("黑体", Font.BOLD, 16);

    /**
     * 获取当前屏幕宽度
     */
    protected static final int WIDTH = Toolkit.getDefaultToolkit().getScreenSize().width;
    /**
     * 获取当前屏幕高度
     */
    protected static final int HEIGHT = Toolkit.getDefaultToolkit().getScreenSize().height;

    //获取工具栏宽高
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    Rectangle maxBounds = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();

    private int taskbarHeight = (int) (screenSize.getHeight() - maxBounds.getHeight());

    private JScrollPane scrollPane;
    private JTextField messageField;

    private static final int DEFAULT_PORT = 8500;

    private static SimpleDateFormat dateFormat = new SimpleDateFormat("[HH:mm:ss] ");

    private BufferedWriter writer;

    public SocketClient() {
        try {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
            //    确保一个漂亮的外观风格

            //更改所有组件字体，没有的待补充
            UIManager.put("Button.font", f2);
            UIManager.put("Label.font", f1);
            UIManager.put("JLabel.font", f1);
            UIManager.put("TextField.font", f1);
            UIManager.put("TextArea.font", f1);
            UIManager.put("ComboBox.font", f1);
            UIManager.put("RadioButton.font", f1);
            UIManager.put("CheckBox.font", f1);
            UIManager.put("MenuItem.font", f1);
            UIManager.put("Menu.font", f1);
            UIManager.put("MenuBar.font", f1);
            UIManager.put("OptionPane.messageFont", f1);
            UIManager.put("OptionPane.buttonFont", f1);

        } catch (Exception e) {
            e.printStackTrace();
        }

        setTitle("测量数据记录_V1.0");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // setSize(800, 300);
        setSize((int) (WIDTH * 0.6), (int) ((HEIGHT - taskbarHeight) * 0.6));
        setLocationRelativeTo(null);//位
        setResizable(false);

        //设置软件图标
        String imagePath = "pic/akx.png";
        if (imagePath!=null){
            setIconImage(Toolkit.getDefaultToolkit().getImage(imagePath));
        }

        JPanel topPanel = new JPanel(new FlowLayout()); // 顶部面板
        JPanel centerPanel = new JPanel(new BorderLayout()); // 中间面板

        JLabel ipLabel = new JLabel("IP:");
        ipField = new JTextField(15);
        ipField.setText("192.168.10.10");

        JLabel portLabel = new JLabel("Port:");

        portField = new JTextField(5);
        // portField.setText("8500");
        portField.setText(String.valueOf(DEFAULT_PORT));

        connectButton = new JButton("启动");
        disconnectButton = new JButton("关闭");
        disconnectButton.setEnabled(false);

        // 将发送按钮和文本框添加到界面中
        JButton sendButton = new JButton("发送");
        messageField = new JTextField(20);

        topPanel.add(ipLabel);
        topPanel.add(ipField);
        topPanel.add(portLabel);
        topPanel.add(portField);
        topPanel.add(connectButton);
        topPanel.add(disconnectButton);

        topPanel.add(messageField);
        topPanel.add(sendButton);

        receivedDataArea = new JTextArea();
        receivedDataArea.setEditable(false);

        //内有滚动条，需要探寻
        scrollPane = new JScrollPane(receivedDataArea);
        centerPanel.add(scrollPane, BorderLayout.CENTER);

        add(topPanel, BorderLayout.NORTH);
        add(centerPanel, BorderLayout.CENTER);


        connectButton.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (connectButton.isEnabled() == false) return;
                super.mouseClicked(e);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        connect();
                    }
                }).start();
            }
        });

        disconnectButton.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (disconnectButton.isEnabled() == false) return;
                super.mouseClicked(e);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        disconnect();
                    }
                }).start();
                connectButton.setEnabled(true);
                disconnectButton.setEnabled(false);
            }
        });

        sendButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String message = messageField.getText(); // 获取文本框中的内容
                sendMessage(message); // 调用发送消息的方法
            }
        });
    }

    // 在 SocketClient 类中添加 sendMessage 方法
    private void sendMessage(String message) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                if (out != null && socket != null && socket.isConnected()) {
                    out.println(message); // 将消息发送到服务器
                    receivedDataArea.append(dateFormat.format(new Date()) + "发送：" + message + "\n"); // 在文本区域显示发送的消息
                    messageField.setText(""); // 清空文本框
                } else {
                    receivedDataArea.append(dateFormat.format(new Date()) + "错误." + message + "\n"); // 显示发送失败消息
                }
            }
        });

    }

    private void connect() {
        String ip = ipField.getText();
        int port = Integer.parseInt(portField.getText());
        try {
            socket = new Socket(ip, port);
            out = new PrintWriter(socket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            if (socket.isConnected()) {
                System.out.println("连接成功");
                JOptionPane.showMessageDialog(null, "连接成功", "结果", JOptionPane.PLAIN_MESSAGE);
                connectButton.setEnabled(false);
                disconnectButton.setEnabled(true);

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String receivedData;
                        try {
                            String path = "excl/";
                            File pathFile = new File(path);
                            if (!pathFile.isDirectory()) {
                                pathFile.mkdirs();
                            }
                            String fileName = "测试数据" + LocalDate.now() + ".csv";
                            File file = new File(pathFile, fileName);
                            if (!file.exists()) {
                                file.createNewFile();
                            }
                            writer = new BufferedWriter(new FileWriter(file, true));

                            // 在读取数据的 while 循环内部
                            while (socket.isConnected() && (receivedData = in.readLine()) != null) {
                                System.out.println("收到的数据: " + receivedData);
                                receivedDataArea.append(dateFormat.format(new Date()) + receivedData + "\n");

                                // 写入csv文件，不带规则
                                // writer.write(dateFormat.format(new Date()) + "," +receivedData);
                                // writer.newLine();
                                // writer.flush();

                                // 将文本框滚动到底部
                                JScrollBar scrollBar = scrollPane.getVerticalScrollBar();
                                scrollBar.setValue(scrollBar.getMaximum());

                                // 使用正则表达式提取+号后的数字
                                String regex = "\\+([0-9]+\\.[0-9]+)";
                                Pattern pattern = Pattern.compile(regex);
                                Matcher matcher = pattern.matcher(receivedData);

                                StringBuilder extractedData = new StringBuilder();

                                // 匹配+号后的数字并写入 CSV 文件
                                while (matcher.find()) {
                                    extractedData.append(matcher.group(1)).append(",");
                                }

                                // 如果有提取的内容，写入 CSV 文件
                                if (extractedData.length() > 0) {
                                    writer.write(dateFormat.format(new Date()) + "," + extractedData.toString());
                                    writer.newLine();
                                    writer.flush();
                                }
                            }

                            writer.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }finally {
                            if (writer!=null){
                                try {
                                    writer.close();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }).start();
            } else {
                JOptionPane.showMessageDialog(
                        null,
                        "连接失败。",
                        "错误",
                        JOptionPane.WARNING_MESSAGE);
            }
        } catch (Exception ex) {
            // 添加日志
            System.out.println("连接失败\r\n原因：" + ex.getMessage());
            JOptionPane.showMessageDialog(
                    null,
                    "连接失败\r\n原因：" + ex.getMessage(),
                    "结果",
                    JOptionPane.ERROR_MESSAGE);
        }
    }

    private void disconnect() {
        try {
            // 关闭 BufferedReader、PrintWriter 和 Socket 对象
            if (in != null) {
                in = null;
            }
            if (out != null) {
                out = null;
            }
            if (socket != null && !socket.isClosed()) {
                socket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                SocketClient client = new SocketClient();
                client.setVisible(true);
            }
        });
    }
}
